<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="candidateForm" :label-width="formLabelWidth" ref="candidateFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="candidateForm.username" placeholder="请输入用户名" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="candidateForm.name" placeholder="请输入姓名" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="密码" prop="password">
              <el-input v-model="candidateForm.password" placeholder="请输入密码" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="candidateForm.gender" placeholder="请选择性别">
                <el-option label="男" :value="1"></el-option>
                <el-option label="女" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                  v-model="candidateForm.birthDate" type="date" placeholder="出生日期" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="candidateForm.contactPhone" placeholder="请输入联系电话" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="candidateForm.email" placeholder="请输入邮箱" maxlength="64"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="省/市/区">
              <el-cascader
                v-model="provinceCityArea"
                :options="provinceCityAreaOptions"
                :props="{ expandTrigger: 'hover', value: 'code', label: 'name' }"
                @change="handleChange"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="家庭地址" prop="address">
              <el-input v-model="candidateForm.address" placeholder="请输入家庭地址" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import candidateApi from '@/api/candidateApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {CandidateForm} from "@/types/req/candidateForm";
import type {Result} from '@/types/result'
import type {Candidate} from "@/types/resp/candidate";
import type {Id} from "@/types/id";
import areas from "@/locales/area.json";

const props = defineProps<Id>()
const candidateFormRef = ref<FormInstance | null>(null);
const candidateForm = reactive<CandidateForm>({
  username: '',
  name: '',
  password: '',
  gender: undefined,
  birthDate: '',
  contactPhone: '',
  email: '',
  province: '',
  city: '',
  area: '',
  address: '',
})
const provinceCityArea = ref<string[]>([])
const provinceCityAreaOptions = areas.provinces
const emit = defineEmits<{
  (e: 'resetCandidateAddEvent'): void;
  (e: 'closeCandidateAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请输入性别', trigger: 'blur' }
  ],
  birthDate: [
    { required: true, message: '请输入出生日期', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initCandidateFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initCandidateFormById = async (id: number) => {
  const resp: Result<Candidate> = await candidateApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(candidateForm, resp.data)
    provinceCityArea.value = []
    if (candidateForm.province) {
      provinceCityArea.value.push(candidateForm.province)
    }
    if (candidateForm.city) {
      provinceCityArea.value.push(candidateForm.city)
    }
    if (candidateForm.area) {
      provinceCityArea.value.push(candidateForm.area)
    }
  }
}

const onReset = () => {
  if (candidateFormRef.value) {
    candidateFormRef.value.resetFields()
  }
  provinceCityArea.value = []
  emit('resetCandidateAddEvent')
}

const onSave = () => {
  if (!candidateFormRef.value) {
    return
  }
  candidateFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await candidateApi.save(candidateForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeCandidateAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const handleChange = (value: string[]) => {
  if (value && value.length > 0) {
    candidateForm.province = value[0]
  }
  if (value && value.length > 1) {
    candidateForm.city = value[1]
  }
  if (value && value.length > 2) {
    candidateForm.area = value[2]
  }
}

const onBack = () => {
  emit('closeCandidateAddEvent')
}
</script>

<style lang="scss">
</style>
